class MyModelGenerator < Rails::Generator::NamedBase
  attr :model, true
  attr :columns, true
  attr :model_classname, true
  def manifest 
    record do |m|
      @model ||= ARGV.shift
      @model_classname = @model.pluralize
      @model = @model.gsub(/(\w)([A-Z])/, '\1_\2').downcase
      @columns = ARGV.collect{|x| x.split(':')} if !ARGV.empty?
      @model_file    = "#{@model}.rb"
      @migrate_file  = "#{get_migration_number()}_create_#{@model.pluralize}.rb"
      @unit_file     = "#{@model}_test.rb"
      @fixtures_file = "#{@model}.yml"
     
      ["#{RAILS_ROOT}/app/models", 
       "#{RAILS_ROOT}/test/unit", 
       "#{RAILS_ROOT}/test/fixtures",
       "#{RAILS_ROOT}/db/migrate"].each do |dir_path|
         rel_path = dir_path.sub(RAILS_ROOT + '/', '')
         if !File.directory?(dir_path)
           Dir.mkdir(dir_path)
           puts "create  #{rel_path}".sub(/^/, " " * 6)
         else
           puts "exists  #{rel_path}".sub(/^/, " " * 6)
         end
      end 
      
      if !File.directory?(models_dir = "#{RAILS_ROOT}/app/models")
        Dir.mkdir(models_dir)
      end 
       
      m.template 'add_model.rhtml',     File.join('app/models', @model_file)
      m.template 'add_unit.rhtml',      File.join('test/unit', @unit_file)
      m.template 'add_fixtures.rhtml',  File.join('test/fixtures', @fixtures_file)
      m.template 'add_migration.rhtml', File.join('db/migrate', @migrate_file)
     
    end
  end
  

  private 
  def get_migration_number
    if migrate_file = Dir["#{RAILS_ROOT}/db/migrate/*rb"].sort.last
     (File.basename(migrate_file).split("_").first.to_i + 1).to_s.rjust(3, "0")
    else
      "001"
    end
  end
end
